package org.stools.plugin.action;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.stools.plugin.common.constants.ExceptionConstants;
import org.stools.plugin.common.constants.PluginConstants;
import org.stools.plugin.exception.PluginException;

/**
 * DelegateSuperAction 抽象代理Action父类,以达到复用的效果
 * @author chunliny
 *
 */
public abstract class DelegateSuperAction implements IObjectActionDelegate {
	
	/**
	 * 默认构造函数
	 */
	public DelegateSuperAction() {

	}
    /**
     * 选择的工程结构
     */
	private IStructuredSelection structSelection;
	/**
	 * 工程对象
	 */
	protected IProject project;
	
	/**
	 * 选择结构工程时的对象获取
	 */
	public void selectionChanged(IAction action, ISelection selection) {
		structSelection = (IStructuredSelection) selection;
		if (structSelection.size() > PluginConstants.SELECT_PROJECT_SIZE) {
			return;
		}
		if (structSelection.getFirstElement() instanceof IJavaProject) {
			Object obj = structSelection.getFirstElement();
			IJavaElement t = (IJavaElement) obj;
			this.project = t.getResource().getProject();
		}
	}
	
	/**
	 * 此方法必须要实现
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
	}
	
	/**
	 * 检查classPath是否存在
	 */
	protected static boolean classPathExists(IClasspathEntry[] entrys, IClasspathEntry entry) {
		int index = 0;
		for (int count = entrys.length; index < count; ++index) {
			if (entrys[index].getPath().equals(entry.getPath())) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 刷新整个工程
	 */
	protected void refresh(String charsetString,IProgressMonitor iProgressMonitor) throws PluginException{
		try {
			project.setDefaultCharset(charsetString);
			project.refreshLocal(PluginConstants.REFRESH_PROJECT_LOAD,iProgressMonitor);
		} catch (CoreException e) {
			throw new PluginException(ExceptionConstants.REFRESH_EXCEPTION_ERROR_ID,ExceptionConstants.REFRESH_EXCEPTION_ERROD_MESSAGE);
		}

	}
	 
}
